package org.example.order.service.impl;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.core.utils.R;
import org.example.order.constant.AlipayConstant;
import org.example.order.dao.OrderDao;
import org.example.order.dao.OrderItemDao;
import org.example.order.dao.PaymentInfoDao;
import org.example.order.entity.PaymentInfoEntity;
import org.example.order.properties.AlipayProperties;
import org.example.order.service.OrderAliPayService;
import org.example.order.utils.InitializationAlipay;
import org.example.order.vo.OrderPayVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 小杰_cc
 * @version 1.0
 */
@Service
public class OrderAliPayServiceImpl implements OrderAliPayService {

    @Autowired
    private InitializationAlipay initializationAlipay;
    @Autowired
    private AlipayProperties alipayProperties;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderItemDao orderItemDao;
    @Autowired
    private PaymentInfoDao paymentInfoDao;

    @Override
    public void pay(String orderSn, HttpServletResponse response) throws AlipayApiException, IOException {
        // 1. 创建Client,通用SDK提供的client，负责调用支付宝的API
        DefaultAlipayClient alipayClient = initializationAlipay.alipayClient();
        // 2. 创建Request
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
//        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setNotifyUrl(alipayProperties.getNotifyUrl());
        request.setReturnUrl(AlipayConstant.RETURN_URL); // 回调地址
        JSONObject entries = new JSONObject();
        // 查询订单信息
        OrderPayVo orderPayVo = orderDao.getOrderPayInfoBySn(orderSn);
        // 找一个支付名称
        List<String> skuNames = orderItemDao.getOrderItemNamePayInfoByOrderSn(orderSn);
        entries.set("order_id", String.valueOf(orderPayVo.getOrderId()));   // 订单id
        entries.set("out_trade_no",orderPayVo.getOrderSn());  // 订单号
        entries.set("total_amount",orderPayVo.getPayAmount());  // 金额
        entries.set("subject",skuNames.get(0));   // 支付名称
        entries.set("product_code","FAST_INSTANT_TRADE_PAY"); // 固定
        entries.set("time_expire", orderPayVo.getOutTime()); // 交易关闭时间
        request.setBizContent(entries.toString());

        String from ="";
        try{
            from = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        }catch (AlipayApiException e){
            e.printStackTrace();
        }

        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(from);
        response.getWriter().flush();
        response.getWriter().close();
    }

    @Override
    @Transactional
    public R<?> payNotify(HttpServletRequest request) throws AlipayApiException {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")){
            HashMap<String, String> params = new HashMap<>();
            Map<String, String[]> parameterMap = request.getParameterMap();

            for (String name : parameterMap.keySet()) {
                params.put(name,request.getParameter(name));
            }

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, alipayProperties.getPublicKey(), "UTF-8"); // 验证签名

            // 支付宝验签
            if (checkSignature){
//                log.info("交易名称:{} ", params.get("subject"));
//                log.info("交易状态:{} " , params.get("trade_status"));
//                log.info("支付宝交易凭证号:{} " , params.get("trade_no"));
//                log.info("商户订单号: {}" , params.get("out_trade_no"));
//                log.info("交易金额: {}" , params.get("total_amount"));
//                log.info("买家在支付宝唯一id:{} " , params.get("buyer_id"));
//                log.info("买家付款时间: {}" , params.get("gmt_payment"));
//                log.info("买家付款金额: {}" , params.get("buyer_pay_amount"));
                PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
//                paymentInfoEntity.setOrderId(Long.parseLong(params.get("order_id")));   // 订单id
                paymentInfoEntity.setOrderSn(params.get("out_trade_no"));   // 商家订单号
                paymentInfoEntity.setAlipayTradeNo(params.get("trade_no"));   // 支付宝交易凭证号
                paymentInfoEntity.setTotalAmount(new BigDecimal(params.get("total_amount")));   // 金额
                paymentInfoEntity.setPaymentStatus(params.get("trade_status"));   // 支付状态
                paymentInfoEntity.setCreateTime(LocalDateTime.now());   // 支付状态
                paymentInfoEntity.setPaymentStatus(params.get("trade_status"));   // 支付状态
                // 添加支付信息
                paymentInfoDao.save(paymentInfoEntity);
                // 修改订单状态
                orderDao.updateOrderStatusBySn(params.get("out_trade_no"), 1);
//                Integer payType = 2;
//                String orderNo = params.get("out_trade_no");
//                String buyerId = params.get("buyer_id");
//                String payment = params.get("gmt_payment");
//                String transactionId = params.get("trade_no");

                return R.ok();
            }
        }
        return R.error();
    }
}
